<script setup>
import { ref } from 'vue'
import { onMounted } from "vue";
import { titleDeleteService, titleModifyService, titleSelectAllService } from "@/api/title.js";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  trainAddService,
  trainDeleteService, trainModifyService,
  trainOpenOrCloseService,
  trainSelectService, trainSelectTitleIdsAndNamesService,
  trainSelectTitlesByTitleIdService
} from "@/api/train.js";
// import { useUserStore } from "@/store/user.js";
import _ from "lodash";
import { MdPreview } from "md-editor-v3";
import moment from 'moment';

/**
 * 添加训练
 * @type {Ref<UnwrapRef<boolean>, UnwrapRef<boolean> | boolean>}
 */
//格式化日期并渲染在表格上
const formatDate = (dateString) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要加1
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
//格式化时间并渲染在表格上
const formatTime = (timeString) => {
  const time = new Date(timeString);
  const hour = String(time.getHours()).padStart(2, '0');
  const minutes = String(time.getMinutes()).padStart(2, '0'); // 如果不足2位前面补0
  const seconds = String(time.getSeconds()).padStart(2, '0');
  return `${hour}：${minutes}：${seconds}`;
}
//是否打开添加训练的模态窗口
const showaddModal = ref(false)
const trainForm = ref({
  trainName: '',
  trainTime: '',
  date: []

  // orginTitleIds: [],
  //   author: userStore.userName,
  // openTrain: false
})
//查询所有题目数据
// const titleList = ref([])
// onMounted(async() => {
//   const res = await titleSelectAllService()
//   if(res.data.status === 'success'){
//     titleList.value = res.data.data
//   }else{
//     ElMessage.error(res.data.info)
//   }
// })
//打开添加题目的模态窗口
const openAddModal = () => {
  showaddModal.value = true
}

//添加训练表单校验
const trainFormRef = ref()
const trainRules = {
  trainName: [
    { required: true, message: '训练名称不能为空', trigger: 'blur' },
    { max: 20, message: '训练名称不能超过20个字', trigger: 'blur' }
  ],
  trainTime: [
    { required: true, message: '训练日期不能为空', trigger: 'change'}
  ],
  date: [
    { required: true, message: '训练时间段不能为空', trigger: 'change'}
  ]
}
//发送添加训练请求
const addTrain = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      trainForm.value.trainTime = moment(trainForm.value.trainTime).format("YYYY-MM-DD HH:mm:ss");
      //解构beginTime和endTime
      trainForm.value.beginTime = trainForm.value.date[0]
      trainForm.value.endTime = trainForm.value.date[1]
      trainForm.value.beginTime = moment(trainForm.value.beginTime).format("YYYY-MM-DD HH:mm:ss");
      trainForm.value.endTime = moment(trainForm.value.endTime).format("YYYY-MM-DD HH:mm:ss");
      const res = await trainAddService(trainForm.value)
      if (res.data.status === 'success') {
        await load()
        ElMessage.success('添加成功')
        showaddModal.value = false
        trainForm.value.trainName = ''
        trainForm.value.date = ''
        trainFormRef.value.resetFields()
      } else {
        ElMessage.error(res.data.info)
      }


      // trainForm.value.orginTitleIds= []
      //   trainForm.value.author= userStore.userName
      // trainForm.value.openTrain= false

    }
  })
}
/**
 * 分页查询训练
 */
//分页查询底部导航栏和搜索框变量
const trainInfo = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const trainNameFuzzy = ref('')
const trainTimeFuzzy = ref('')
const beginTimeFuzzy = ref('')
const endTimeFuzzy = ref('')
const total = ref(0)
const selectIds = Array
const handleSelectionChange = (selection) => {
  selectIds.value = selection.map(item => item.trainId)
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  load()
}
const handleSizeChange = (val) => {
  pageSize.value = val
  load()
}
//页面加载的时候发送一次查询请求
onMounted(() => {
  load()
})
const load = async () => {
  //日期转换
  if (trainTimeFuzzy.value) {
    trainTimeFuzzy.value = moment(trainTimeFuzzy.value).format("YYYY-MM-DD HH:mm:ss");
  }
  if (beginTimeFuzzy.value) {
    beginTimeFuzzy.value = moment(beginTimeFuzzy.value).format("YYYY-MM-DD HH:mm:ss");
  }
  if (endTimeFuzzy.value) {
    endTimeFuzzy.value = moment(endTimeFuzzy.value).format("YYYY-MM-DD HH:mm:ss");
  }
  const res = await trainSelectService(currentPage.value, pageSize.value, trainNameFuzzy.value, trainTimeFuzzy.value, beginTimeFuzzy.value, endTimeFuzzy.value)
  if (res.data.status === 'success') {
    trainInfo.value = res.data.data.list
    total.value = res.data.data.totalCount
  } else {
    ElMessage.error(res.data.info)
  }
}

/**
 * 开启/关闭训练
 */
const modifyOpenTrain = async (train) => {
  const res = await trainOpenOrCloseService(train.trainId, train.openTrain)
  if (res.data.status === 'success') {
    train.updateTime = res.data.data
  } else {
    ElMessage.error('操作有误，请稍后再试')
  }
}
/**
 * 删除训练
 */
const deleteTrain = (trainId) => {
  // if (train.openTrain) {
  //   ElMessage.warning('无法删除已开启的训练')
  //   return
  // }
  // const trainIds = Array.of(train.trainId)
  ElMessageBox.confirm(
    '确定要删除该训练吗?',
    '警告',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res = await trainDeleteService(trainId)
      if (res.data.status === 'success') {
        await load()
        ElMessage.success('删除成功')
      } else {
        ElMessage.error(res.data.info)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//批量删除
const deleteTrains = async () => {
  //非空判断
  if (selectIds.value == null) {
    ElMessage.info('未选中任何一次训练')
    return
  }
  if (selectIds.value != null && selectIds.value.length === 0) {
    ElMessage.info('未选中任何一次训练')
    return
  }
  ElMessageBox.confirm(
    '确定要删除所有选中的训练吗?',
    '警告',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res = await trainDeleteService(selectIds.value)
      if (res.data.status === 'success') {
        await load()
        ElMessage.success('删除成功')
      } else {
        ElMessage.error(res.data.info)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
/**
 * 修改训练
 */
//添加修改题目的校验规则
const modifyTrainFormRef = ref()
const modifyTrainRules = {
  trainName: [
    { required: true, message: '训练名称不能为空', trigger: 'blur' },
    { max: 20, message: '训练名不能超过20个字', trigger: 'blur' }
  ],
}
//是否打开修改训练模态窗口
const showModifyModal = ref(false)
//修改表单数据
const trainModifyForm = ref('')
const ModifyTrain = async (train) => {
  //判断训练是否已经开启，如果开启，则不让修改
  // if (train.openTrain) {
  //   ElMessage.warning('无法修改已开启的训练')
  //   return
  // }
  //将train的数据深拷贝给修改表单数据
  trainModifyForm.value = _.cloneDeep(train)
  trainModifyForm.value.date = [trainModifyForm.value.beginTime, trainModifyForm.value.endTime]
  console.log(trainModifyForm.value)
  //根据训练id查询关联的题目数据
  // if (train.question <= 0) {
  //   showModifyModal.value = true
  //   return
  // }
  // const res = await trainSelectTitleIdsAndNamesService(train.trainId)
  // if (res.data.status === 'success') {
  //   trainModifyForm.value.titleIds = res.data.data.titleIds
  //   trainModifyForm.value.titleNames = res.data.data.titleNames
  // } else {
  //   ElMessage('查询题目信息失败')
  //   return
  // }
  showModifyModal.value = true
}
//发送修改训练请求
const modifyTrain = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      trainModifyForm.value.trainTime = moment(trainModifyForm.value.trainTime).format("YYYY-MM-DD HH:mm:ss");
      //解构beginTime和endTime
      trainModifyForm.value.beginTime = trainModifyForm.value.date[0]
      trainModifyForm.value.endTime = trainModifyForm.value.date[1]
      trainModifyForm.value.beginTime = moment(trainModifyForm.value.beginTime).format("YYYY-MM-DD HH:mm:ss");
      trainModifyForm.value.endTime = moment(trainModifyForm.value.endTime).format("YYYY-MM-DD HH:mm:ss");
      const res = await trainModifyService(trainModifyForm.value)
      if (res.data.status === 'success') {
        await load()
        ElMessage.success('修改成功')
      } else {
        ElMessage.error(res.data.info)
      }
      showModifyModal.value = false
    }
  })
}
/**
 * 预览训练内容
 */
const showTitles = ref(false)
const titles = ref([])
const showTitlesModal = async (trainId) => {
  //根据训练id查询训练所关联的题目数据
  const res = await trainSelectTitlesByTitleIdService(trainId)
  if (res.data.status === 'success') {
    titles.value = res.data.data
    showTitles.value = true
  } else {
    ElMessage.error(res.data.info)
  }
}
/**
 * 展示题目内容
 */
const showContent = ref(false)
const currentTitleContent = ref('')
const showContentModal = (titleContent) => {
  currentTitleContent.value = titleContent
  showContent.value = true
}
</script>

<template>
  <!--  模态窗口-->
  <!--  添加训练模态窗口-->
  <el-dialog v-model="showaddModal" title="添加训练" width="500">
    <el-form ref="trainFormRef" :rules="trainRules" :model="trainForm">
      <el-form-item prop="trainName" label="训练名称&nbsp&nbsp&nbsp">
        <el-input v-model="trainForm.trainName" autocomplete="off" />
      </el-form-item>
      <el-form-item prop="trainTime" label="训练日期&nbsp&nbsp&nbsp">
        <el-date-picker v-model="trainForm.trainTime" type="date" placeholder="选择日期" :size="size" />
      </el-form-item>
      <el-form-item prop="date" label="训练时间段">
        <el-time-picker v-model="trainForm.date" is-range range-separator="To" start-placeholder="开始时间"
          end-placeholder="结束时间" />
      </el-form-item>
      <!-- <el-form-item label="题目" :label-width="50">
        <el-select v-model="trainForm.orginTitleIds" :multiple-limit="10" multiple clearable placeholder="请选择题目">
          <el-option
            v-for="(item,index) in titleList"
            :key="index"
            :value="item.titleId"
            :label="item.titleName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否开启" style="float: left">
        <el-switch
          v-model="trainForm.openTrain"
          class="ml-2"
          inline-prompt
          active-text="是"
          inactive-text="否"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
        />
      </el-form-item> -->
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showaddModal = false">取消</el-button>
        <el-button type="primary" @click="addTrain(trainFormRef)">
          添加
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--  修改训练模态窗口-->
  <el-dialog v-model="showModifyModal" title="修改训练" width="500">
    <el-form ref="trainFormRef" :rules="trainRules" :model="trainModifyForm">
      <el-form-item prop="trainName" label="训练名称&nbsp">
        <el-input v-model="trainModifyForm.trainName" autocomplete="off" />
      </el-form-item>
      <el-form-item prop="trainTime" label="训练日期&nbsp&nbsp&nbsp">
        <el-date-picker v-model="trainModifyForm.trainTime" type="date" placeholder="选择日期" :size="size" />
      </el-form-item>
      <el-form-item prop="date" label="训练时间段">
        <el-time-picker v-model="trainModifyForm.date" is-range range-separator="To" start-placeholder="开始时间"
          end-placeholder="结束时间" />
      </el-form-item>
      <!-- <el-form-item prop="trainName" label="训练名称">
        <el-input v-model="trainModifyForm.trainName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="题目" :label-width="50">
        <el-select v-model="trainModifyForm.titleNames" :multiple-limit="10" multiple clearable placeholder="请选择题目">
          <el-option v-for="(item, index) in titleList" :key="index" :value="item.titleName"
            :label="item.titleName"></el-option>
        </el-select>
      </el-form-item> -->
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showModifyModal = false">取消</el-button>
        <el-button type="primary" @click="modifyTrain(trainFormRef)">
          修改
        </el-button>
      </div>
    </template>
  </el-dialog>
  <div>
    <!--    展示训练内容模态窗口-->
    <el-dialog v-model="showTitles" title="训练内容" width="800">
      <el-form>
        <ul class="show-titles" v-for="(item, index) in titles" :key="index">
          <li style="float: left">第{{ index + 1 }}题</li>
          <li style="cursor: pointer;color: blue" @click="showContentModal(item.titleContent)">{{ item.titleName }}</li>
        </ul>
      </el-form>
    </el-dialog>
    <!--    展示题目内容模态窗口-->
    <el-dialog v-model="showContent" title="题目内容" width="800">
      <el-form>
        <MdPreview class="red" style="background: #3d3d3d" :modelValue="currentTitleContent">
        </MdPreview>
      </el-form>
    </el-dialog>
    <!--      功能栏-->
    <div>
      <el-card style="float: left;margin-bottom: 20px">
        <el-button @click="openAddModal" type="primary">添加训练</el-button>
        <!-- <el-button @click="deleteTrains" type="danger">批量删除</el-button> -->
      </el-card>
      <!--        搜索框-->
      <el-card class="train-search">
        <span>
          <h1>训练名称:</h1>
        </span>
        <input v-model="trainNameFuzzy" @keyup.enter.native="load">
        <!-- 训练日期筛选 -->
        <span style="margin-left: 20px;">
          <h1>训练日期</h1>
        </span>
        <el-date-picker @change="load" v-model="trainTimeFuzzy" type="date" placeholder="选择日期"></el-date-picker>
        

        <!-- <span>
          <h1>开始时间</h1>
          <el-time-picker @change="load"  v-model="beginTimeFuzzy" placeholder="开始时间" />
        </span>
        <span>
          <h1>结束时间</h1>
          <el-time-picker @change="load"  v-model="endTimeFuzzy" placeholder="结束时间" />
        </span> -->

        <el-button type="warning" @click="load">搜索</el-button>
      </el-card>
    </div>
    <!--      表格-->
    <el-table ref="multipleTableRef" :data="trainInfo" stripe style="width: 100%;margin-top: 30px"
      @selection-change="handleSelectionChange">
      <el-table-column width="55" />
      <el-table-column property="trainId" label="编号" width="100" />
      <el-table-column style="z-index: 100" property="trainName" label="训练名" width="150">
        <!-- <template #default="scope">
            <div style="cursor: pointer;color: blue" @click="showTitlesModal(scope.row.trainId)">{{scope.row.trainName}}</div>
          </template> -->
      </el-table-column>
      <!-- <el-table-column  property="question" label="题目数" width="100" > -->
      <!--          <template #default="scope">-->
      <!--            <div style="cursor: pointer;color: blue" @click="showTitlesModal(scope.row.titleId)">{{scope.row.question}}</div>-->
      <!--          </template>-->
      <!-- </el-table-column> -->
      <!-- <el-table-column  property="author" label="作者" width="200" /> -->
      <!-- <el-table-column  property="openTrain" label="是否开启" width="150" > -->
      <!-- <template #default="scope">
            <el-switch
              v-model="scope.row.openTrain"
              class="ml-2"
              inline-prompt
              active-text="是"
              inactive-text="否"
              @change="modifyOpenTrain(scope.row)"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            />
          </template> -->

      <!-- </el-table-column>> -->
      <el-table-column property="trainTime" label="训练日期" width="150">
        <template #default="scope">
          {{ formatDate(scope.row.trainTime) }}
        </template>
      </el-table-column>
      <el-table-column property="beginTime" label="开始时间" width="150">
        <template #default="scope">
          {{ formatTime(scope.row.beginTime) }}
        </template>
      </el-table-column>
      <el-table-column property="endTime" label="结束时间" width="150">
        <template #default="scope">
          {{ formatTime(scope.row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column property="createTime" label="创建时间" width="180" />
      <el-table-column property="updateTime" label="最近修改时间" width="180" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="info" size="small" @click="ModifyTrain(scope.row)">
            修改
          </el-button>
          <el-button size="small" type="danger" @click="deleteTrain(scope.row.trainId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页组件-->
    <el-card style="margin-top: 20px;float: right;">
      <div class="demo-pagination-block">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[2, 5, 10, 20]"
          size="large" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @current-change="handleCurrentChange" @size-change="handleSizeChange" />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
/*搜索样式*/
.train-search {
  width: 1000px;
  float: left;
  margin-left: 20px;
}

.train-search span {
  float: left;
}

.train-search input {
  float: left;
  height: 25px;
  border: solid 2px;
  margin-top: 2px;
}

/*展示题目列表样式*/
.show-titles {
  text-align: center;
  font-size: 30px;
  list-style-type: none;
}

/*设置markdown字体颜色*/
:deep() div.default-theme p {
  color: white;
}

/*表头样式*/
:deep() th.el-table__cell {
  color: black;
  font-size: 20px;
}
</style>
